<template>
  <a-spin :spinning="spinning">
    <k-form-design ref="kfd" toolbarsTop :destroyOnClose="true" :showToolbarsText="true" :showHead="false"
      :toolbars="design.toolbars" @save="editFormSave">
      <!-- 左侧操作区域插槽 start -->
      <template slot="left-action">
        <a-tooltip title="发布表单" @click="editFormPublic">
          <a>
            <a-icon type="build" />
            <span>发布</span>
          </a>
        </a-tooltip>
      </template>
      <!-- 左侧操作区域插槽 end -->
      <!-- 右侧操作区域插槽 start -->
      <template slot="right-action">
        <div class="margin-right-xl" v-if="!this.fromApp">
          <a-tooltip :title="form.name"><span class="text-bold">{{ form.name }}</span></a-tooltip>
          <a-divider type="vertical" />
          <a-tooltip title="关闭">
            <a @click="cancel" style="color: #ff4d4f">
              <a-icon type="close" />
              <span>关闭</span>
            </a>
          </a-tooltip>
        </div>
      </template>
      <!-- 右侧操作区域插槽 end -->
    </k-form-design>
  </a-spin>
</template>

<script>
import Vue from "vue";
import KFormDesign from "@/pages/system/agile/components/packages";
import "@/pages/system/agile/components/styles/form-design.less";

Vue.use(KFormDesign);

import {
  findById,
  editSave,
  editPublic,
  tableField,
} from "@/services/system/agile/form/desinger";

export default {
  name: "businessdatadesinger",

  data() {
    return {
      design: {
        toolbars: [
          "save",
          "preview",
          "importJson",
          "exportJson",
          "exportCode",
          "undo",
          "redo",
          "reset",
        ],
      },

      form: {
        configId: "",
        name: "",
      },

      loading: false,
      spinning: false,

      controls: [],
      edit: {
        controls: [], //所有控件信息
      },
    };
  },

  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    fromApp: {
      type: Boolean,
      default: false,
    }, //是否从App处来
    configId: String,
    title: {
      type: String,
    },
  },
  mounted() {
    this.find();
  },
  methods: {
    /**
     * 取消
     */
    cancel() {
      this.$emit("close");
    },

    /**
     * 保存表单设计
     */
    editFormSave(values) {
      let that = this;
      this.controls = JSON.parse(values);
      let param = {
        configId: this.form.configId,
        saveJson: values,
      };
      that.$loading.show({ text: "保存中,请稍等..." });
      editSave(param).then(function (result) {
        that.$loading.hide();
        if (result.code === that.eipResultCode.success) {
          that.$message.success(result.msg);
        } else {
          that.$message.error(result.msg);
        }
      });
    },

    /**
     * 获取控件字段类型
     */
    editFormFieldType(control) {
      switch (control.type) {
        case "input": //输入框
        case "textarea": //文本框
        case "user":
        case "organization":
          var maxLength = control.options.maxLength
            ? control.options.maxLength
            : 1024;
          return `nvarchar(${maxLength})`;
        case "number": //数字输入框
          //判断是否具有小数点
          if (control.precision) {
            return `numeric(18, ${control.precision})`;
          } else {
            return `int`;
          }
        case "checkbox":
        case "radio":
        case "select":
        case "datalist":
          return `nvarchar(512)`;
        case "editor":
        case "sign":
          return `text`;
        case "district":
          return `nvarchar(512)`;
        case "date":
          return `datetime`;
        case "time":
          return `nvarchar(8)`;
        case "icon":
          return `nvarchar(64)`;
        case "rate":
          return `numeric(18, 1)`;
        case "slider":
          return `numeric(18, 2)`;
        case "switch":
          return `bit`;
      }
    },

    /**
     * 发布表单设计
     */
    editFormPublic() {
      let that = this;
      const modal = this.$confirm({
        okText: "确认",
        cancelText: "取消",
        title: "表单发布提示",
        content: "若已发布会覆盖原来表结构，且不可恢复？",
        onOk() {
          modal.destroy();
          var json = that.$refs.kfd.getValue();
          let fieldSchema = that.$refs.kfd.getFieldSchema();
          let param = {
            configId: that.form.configId,
            saveJson: JSON.stringify(json),
            publicJson: JSON.stringify(json),
            columnJson: JSON.stringify(fieldSchema),
          };

          //创建修改字段
          let columns = [];
          //解析字段
          fieldSchema
            .filter((f) => f.layoutType != "batch" && f.type != "text")
            .forEach((control) => {
              let column = {
                issingle: true,
                name: control.model, //字段名
                type: that.editFormFieldType(control), //字段类型
                description: control.label, //描述
                null: control.rules.filter((f) => f.required).length == 0, //是否可为空
                controlType: control.type, //组件类型
              };
              switch (column.controlType) {
                case "district":
                case "checkbox": //复选框
                  column.issingle = false; //是否为单选,若为多选则新建关系表
                  break;
                case "select": //选择框
                case "organization": //组织架构
                case "user": //用户
                  column.issingle = !control.options.multiple;
                  break;
                default:
                  break;
              }
              columns.push(column);
            });

          //得到子表
          var batchNames = [],
            batchLabels = [];
          fieldSchema
            .filter((f) => f.layoutType == "batch")
            .forEach((item) => {
              if (batchNames.indexOf(item.layoutTypeModel) == -1) {
                batchNames.push(item.layoutTypeModel);
                batchLabels.push(item.layoutTypeLabel);
              }
            });

          batchNames.forEach((item, index) => {
            var batchColumns = fieldSchema.filter(
              (f) => f.layoutTypeModel == item
            ); //得到子表控件
            let layoutColumns = [];
            batchColumns.forEach((control) => {
              let column = {
                issingle: true,
                name: control.model, //字段名
                type: that.editFormFieldType(control), //字段类型
                description: control.label, //描述
                null: control.rules.filter((f) => f.required).length == 0, //是否可为空
                controlType: control.type, //组件类型
              };
              switch (column.controlType) {
                case "checkbox": //复选框
                  column.issingle = false; //是否为单选,若为多选则新建关系表
                  break;
                case "select": //选择框
                  column.issingle = !control.options.multiple;
                  break;
                case "organization": //组织架构
                case "dictionary": //字典
                case "user": //用户
                  break;
                default:
                  break;
              }
              layoutColumns.push(column);
            });

            let batchColumn = {
              name: item, //字段名
              type: "", //字段类型
              description: batchLabels[index], //描述
              controlType: "batch", //组件类型
              value: JSON.stringify(layoutColumns),
            };

            columns.push(batchColumn);
          });

          // if (columns.length == 0) {
          //   that.$message.error("请添加控件");
          //   return false;
          // }
          let publicParam = {
            configId: that.form.configId,
            columns: JSON.stringify(columns),
          };
          that.$loading.show({ text: "发布中,请稍等..." });
          tableField(publicParam).then(function (result) {
            if (result.code === that.eipResultCode.success) {
              editPublic(param).then(function (result) {
                that.$loading.hide();
                if (result.code === that.eipResultCode.success) {
                  that.$message.success(result.msg);
                } else {
                  that.$message.error(result.msg);
                }
              });
            } else {
              that.$loading.hide();
              that.$message.error(result.msg);
            }
          });
        },
        onCancel() { },
      });
    },

    /**
     * 根据Id查找
     */
    find() {
      let that = this;
      that.spinning = true;
      findById(this.configId).then(function (result) {
        let form = result.data;
        that.form.name = form.name;
        that.form.configId = that.configId;
        if (form.saveJson) {
          that.$refs.kfd.handleSetData(JSON.parse(form.saveJson));
        } else {
          let def = {
            list: [],
            config: {
              layout: "horizontal",
              labelCol: {
                xs: 4,
                sm: 4,
                md: 4,
                lg: 4,
                xl: 4,
                xxl: 4,
              },
              wrapperCol: {
                xs: 18,
                sm: 18,
                md: 18,
                lg: 18,
                xl: 18,
                xxl: 18,
              },
              event: {
                before: "",
                after: "",
              },
              api: {
                before: "",
                after: "",
              },
              button: {
                submit: {
                  name: "保存",
                  success: 0,
                },
              },
              hideRequiredMark: false,
              width: 850,
              unit: "px",
              formWidth: 800,
              formWidthUnit: "px",
              top: "100", //距离顶部高度,默认100
              centered: false, //垂直居中
              customStyle: "",
            },
          };
          that.$refs.kfd.handleSetData(def);
        }
        that.spinning = false;
        that.eipAgileDesinger.kfd = that.$refs.kfd;
      });
    },

    /**
     * 触发保存
     */
    save() {
      this.$refs.kfd.handleSave();
    },
  },
};
</script>

<style lang="less" scoped></style>
